<template>
  <div class="login-container">
    <!-- 顶部工具栏 -->
    <div class="top-bar">
      <!-- <el-switch
        v-model="isDark"
        inline-prompt
        active-icon="Moon"
        inactive-icon="Sunny"
        @change="toggleTheme"
      /> -->
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <div class="login-bg-img-bar">
      <div class="login-bg-img" :style="{ 'background-size': `${zoom}%` }"></div>
    </div>
    <!-- 标题 -->
    <div class="login-title">
      <div class="login-title-main">
        <span>BMS云系统</span>
        <img src="/src/assets/images/u18.svg" />
      </div>
      <div class="login-title-sub">集智云BMS</div>
    </div>
    <!-- 登录表单 -->
    <el-card class="login-card">
      <div class="text-left relative">
        <h2>{{ $t("login.login") }}</h2>
        <!-- <el-tag class="ml-2 absolute-rt">{{ defaultSettings.version }}</el-tag> -->
      </div>

      <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <div class="input-wrapper">
            <i-ep-user class="mx-2" />
            <el-input ref="username" v-model="loginData.username" :placeholder="$t('login.username')" name="username"
              size="large" class="h-[48px]" />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
          <el-form-item prop="password">
            <div class="input-wrapper">
              <i-ep-lock class="mx-2" />
              <el-input v-model="loginData.password" :placeholder="$t('login.password')" type="password" name="password"
                @keyup="checkCapslock" @keyup.enter="onShowCaptcha" size="large" class="h-[48px] pr-2" show-password />
            </div>
          </el-form-item>
        </el-tooltip>

        <!-- 验证码 -->
        <!-- <el-form-item prop="captchaCode">
          <div class="input-wrapper">
            <svg-icon icon-class="captcha" class="mx-2" />
            <el-input
              v-model="loginData.captchaCode"
              auto-complete="off"
              size="large"
              class="flex-1"
              :placeholder="$t('login.captchaCode')"
              @keyup.enter="handleLoginSubmit"
            />

            <el-image
              @click="getCaptcha"
              :src="captchaBase64"
              class="captcha-image"
            />
          </div>
        </el-form-item> -->

        <!-- 登录按钮 -->
        <el-button :loading="loading" type="primary" size="large" class="w-full" @click.prevent="onShowCaptcha">
          {{ $t("login.login") }}
        </el-button>

        <!-- 账号密码提示 -->
        <!-- <div class="mt-10 text-sm">
          <span>{{ $t("login.username") }}: admin</span>
          <span class="ml-4">{{ $t("login.password") }}: 123456</span>
        </div> -->
      </el-form>
    </el-card>
    <el-dialog v-model="dialogFormVisible" title="验证码" width="345"
      style="border: 1px solid var(--el-border-color); border-radius: 5px">
      <slide-verify ref="block" :slider-text="text" :accuracy="accuracy" :imgs="captchaImgs" @again="onAgain"
        @success="onSuccess" @fail="onFail" @refresh="onRefresh" />
      <div>{{ msg }}</div>
    </el-dialog>
    <!-- ICP备案 -->
    <!-- <div class="icp-info" v-show="icpVisible">
      <p>
        Copyright © 2021 - 2024 youlai.tech All Rights Reserved. 有来技术
        版权所有
      </p>
      <p>皖ICP备20006496号-3</p>
    </div> -->
  </div>
</template>

<script setup lang="ts">
// 外部库和依赖
import { LocationQuery, useRoute } from "vue-router";

// 内部依赖
import { useSettingsStore, useUserStore } from "@/store";
import AuthAPI, { LoginData } from "@/api/auth";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

// 类型定义
import type { FormInstance } from "element-plus";

// 导入 login.scss 文件
import "@/styles/login.scss";

import SlideVerify, { type SlideVerifyInstance } from "vue3-slide-verify";
import "vue3-slide-verify/dist/style.css";
import { ref } from "vue";

// 使用导入的依赖和库
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const route = useRoute();
// 窗口高度
const { height } = useWindowSize();
// 国际化 Internationalization
const { t } = useI18n();

// 是否暗黑模式
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
// 是否显示 ICP 备案信息
const icpVisible = ref(true);
// 按钮 loading 状态
const loading = ref(false);
// 是否大写锁定
const isCapslock = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
//图片放大缩小
const zoom = ref<any>(250);
// 计算属性来生成样式对象

for (let index = 70; index < 250; index++) {
  setTimeout(() => {
    zoom.value = 320 - index;
  }, (index - 70) * 8);
}

// 登录表单ref
const loginFormRef = ref<FormInstance>();

const loginData = ref<LoginData>({
  username: "admin",
  password: "123456",
} as LoginData);

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
  };
});

/** 获取验证码 */
const dialogFormVisible = ref(false);
const text = ref<string>("向右滑动->");
const accuracy = ref(15);

const msg = ref("");
const block = ref<SlideVerifyInstance>();

// const captchaImgs = ref([
//   "https://monoplasty.github.io/vue3-slide-verify/assets/img3.5b97d210.jpg",
//   "https://monoplasty.github.io/vue3-slide-verify/assets/img2.3217378f.jpg",
//   "https://monoplasty.github.io/vue3-slide-verify/assets/img4.708137a5.jpg",
//   "https://monoplasty.github.io/vue3-slide-verify/assets/img.b6b220bc.jpg",
//   "https://monoplasty.github.io/vue3-slide-verify/assets/img1.182c2f76.jpg",
// ]);
import { captchaImg } from './captchaImgs'
const captchaImgs = captchaImg;

const onShowCaptcha = () => {
  dialogFormVisible.value = true;
  handleClick();
};

const onAgain = () => {
  msg.value = "检测到非人为操作的哦！ try again";
  // 刷新
  block.value?.refresh();
};

const onSuccess = (times: number) => {
  msg.value = "";
  //msg.value = `login success, 耗时${(times / 1000).toFixed(1)}s`;
  handleLoginSubmit();
  dialogFormVisible.value = false;
};

const onFail = () => {
  msg.value = "验证不通过";
};

const onRefresh = () => {
  msg.value = "点击了刷新小图标";
};

const handleClick = () => {
  // 刷新
  block.value?.refresh();
  msg.value = "";
};
// function getCaptcha() {
//   AuthAPI.getCaptcha().then((data) => {
//     loginData.value.captchaKey = data.captchaKey;
//     captchaBase64.value = data.captchaBase64;
//   });
// }

/** 登录表单提交 */
function handleLoginSubmit() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const { path, queryParams } = parseRedirect();
          console.log("path", path);
          console.log("queryParams", queryParams);

          router.push({ path: '/dashboard' });
        })
        .catch(() => {
          //getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/** 解析 redirect 字符串 为 path 和  queryParams */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

/** 主题切换 */
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}
</script>

<style lang="scss" scoped></style>
